from flask import Blueprint, request, jsonify
import json
from backend.app.config import SD_CONFIG_FILE
from backend.app.utils.http import handle_request_error

bp = Blueprint('sd_config', __name__)


@bp.route('/save_config', methods=['POST'])
@handle_request_error
def save_config():
    try:
        data = request.json
        config_name = data.get('name', 'default')
        is_default = data.get('is_default', False)
        config_data = {
            'negative_prompt': data.get('negative_prompt', ''),
            'width': data.get('width', 512),
            'height': data.get('height', 512),
            'steps': data.get('steps', 20),
            'cfg_scale': data.get('cfg_scale', 7),
            'sampler_name': data.get('sampler_name', 'Euler a'),
            'model': data.get('model', ''),
            'seed': data.get('seed', -1),
            'enable_hr': data.get('enable_hr', False),
            'denoising_strength': data.get('denoising_strength', 0.7),
            'upscaler_scale': data.get('upscaler_scale', 2),
            'lora_model': data.get('lora_model', ''),
            'lora_weight': data.get('lora_weight', 0.5),
            'batch_count': data.get('batch_count', 1),
            'batch_size': data.get('batch_size', 1),
            'hr_resize_mode': data.get('hr_resize_mode', 'scale'),
            'hr_target_width': data.get('hr_target_width', 1024),
            'hr_target_height': data.get('hr_target_height', 1024),
            'is_default': is_default
        }

        # 读取现有配置
        try:
            with open(SD_CONFIG_FILE, 'r', encoding='utf-8') as f:
                configs = json.load(f)
        except:
            configs = {}

        # 如果设置为默认配置，清除其他配置的默认标记
        if is_default:
            for name in configs:
                if 'is_default' in configs[name]:
                    configs[name]['is_default'] = False

        # 更新配置
        configs[config_name] = config_data

        # 保存配置
        with open(SD_CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(configs, f, indent=2, ensure_ascii=False)

        return jsonify({
            'data': {
                'success': True,
                'message': '配置保存成功'
            }
        })
    except Exception as e:
        return jsonify({
            'data': {
                'success': False,
                'error': str(e)
            }
        }), 500


@bp.route('/load_config', methods=['GET'])
@handle_request_error
def load_config():
    try:
        config_name = request.args.get('name', 'default')

        # 读取配置
        try:
            with open(SD_CONFIG_FILE, 'r', encoding='utf-8') as f:
                configs = json.load(f)
        except:
            configs = {}

        config = configs.get(config_name, {})

        return jsonify({
            'data': {
                'success': True,
                'config': config
            }
        })
    except Exception as e:
        return jsonify({
            'data': {
                'success': False,
                'error': str(e)
            }
        }), 500


@bp.route('/list_configs', methods=['GET'])
@handle_request_error
def list_configs():
    try:
        # 读取配置
        try:
            with open(SD_CONFIG_FILE, 'r', encoding='utf-8') as f:
                configs = json.load(f)
        except:
            configs = {}

        # 获取默认配置名称
        default_config = None
        for name, config in configs.items():
            if config.get('is_default', False):
                default_config = name
                break

        return jsonify({
            'data': {
                'success': True,
                'configs': list(configs.keys()),
                'default_config': default_config
            }
        })
    except Exception as e:
        return jsonify({
            'data': {
                'success': False,
                'error': str(e)
            }
        }), 500
